package com.dzl.admin;

import com.alibaba.fastjson.JSONObject;
import com.dzl.admin.pojo.SysAdmin;
import com.dzl.admin.pojo.query.SysAdminQuery;
import com.dzl.admin.pojo.vo.LoginSysAdminVo;
import com.dzl.admin.pojo.vo.SysAdminVo;
import com.dzl.admin.service.SysAdminService;
import com.dzl.base.controller.BaseController;
import com.dzl.constant.CommonConstants;
import com.dzl.util.*;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * 企服服务端用户表(SysAdmin)表控制层
 * @author caobucao
 * @since 2021-05-13 15:35:06
 */
@Slf4j
@RestController
@RequestMapping("sysAdmin")
public class SysAdminController extends BaseController {

    @Autowired
    private SysAdminService sysAdminService;

    /**
     * 登录验证手机号
     * @param query phone:手机号
     * @date 2022/01/07 17:56
     * @author liuguanjun
     */
    @PostMapping(value="/loginVerifyPhone")
    public JsonResult<Map> loginVerifyPhone(@RequestBody JSONObject query) {
        String phone=query.getString("phone");
        if(EmptyUtils.isEmpty(phone)) {
            return JsonResult.paramErrWithMsg("请输入手机号");
        }
        if(phone.length()!=11) {
            return JsonResult.paramErrWithMsg("请输入正确的手机号");
        }
        //登录
        Map result = sysAdminService.loginVerifyPhone(phone);
        return JsonResult.success(result);
    }


    /**
     * 登录验证密码
     * @param query code:验证码  userId:用户id  password:密码  passwords:密码再次输入
     * @date 2022/01/07 17:56
     * @author liuguanjun
     */
    @PostMapping(value="/loginVerifyPassword")
    public JsonResult<String> loginVerifyPassword(@RequestBody JSONObject query) {
        String code=query.getString("code");
        Integer userId=query.getInteger("userId");
        String password=query.getString("password");
        String passwords=query.getString("passwords");
        if(EmptyUtils.isEmpty(userId)) {
            return JsonResult.paramErrWithMsg("用户id不能传空");
        }
        SysAdmin sysAdmin = sysAdminService.selectByPrimaryKey(userId);
        if(EmptyUtils.isEmpty(sysAdmin)){
            return JsonResult.failWithMsg("账号不存在！");
        }
        if(EmptyUtils.isEmpty(sysAdmin.getPassword())){
            if(EmptyUtils.isEmpty(code)) {
                return JsonResult.paramErrWithMsg("请输入验证码");
            }
            Object code_ = RedisUtil.get(sysAdmin.getPhone() + ":1000" );
            if(code_==null || !code.equals(code_.toString())){
                return JsonResult.paramErrWithMsg("验证码不正确");
            }
            if(EmptyUtils.isEmpty(password)) {
                return JsonResult.paramErrWithMsg("请输入密码");
            }
            if(EmptyUtils.isEmpty(passwords)) {
                return JsonResult.paramErrWithMsg("请输入密码");
            }
            if(!passwords.equals(password)) {
                return JsonResult.paramErrWithMsg("两次密码不一致，请重新输入");
            }
            if(password.length()<8 || password.length()>12){
                return JsonResult.paramErrWithMsg("密码长度必须8到12位");
            }
        }else{
            if(EmptyUtils.isEmpty(password)) {
                return JsonResult.paramErrWithMsg("请输入密码");
            }
        }
        //登录
        String token=sysAdminService.loginVerifyPassword(sysAdmin, password);
        return JsonResult.success(token);
    }

    /**
     * 忘记密码
     * @param query code:验证码  userId:用户id  password:密码  passwords:密码再次输入
     * @date 2022/01/08 14:28
     * @author liuguanjun
     */
    @PostMapping(value="/loginSetNewPassword")
    public JsonResult<Integer> loginSetNewPassword(@RequestBody JSONObject query) {
        String code=query.getString("code");
        Integer userId=query.getInteger("userId");
        String password=query.getString("password");
        String passwords=query.getString("passwords");
        if(EmptyUtils.isEmpty(userId)) {
            return JsonResult.paramErrWithMsg("用户id不能传空");
        }
        SysAdmin sysAdmin = sysAdminService.selectByPrimaryKey(userId);
        if(EmptyUtils.isEmpty(sysAdmin)){
            return JsonResult.failWithMsg("账号不存在！");
        }
        if(EmptyUtils.isEmpty(code)) {
            return JsonResult.paramErrWithMsg("请输入验证码");
        }
        Object code_ = RedisUtil.get(sysAdmin.getPhone() + ":1000" );
        if(code_==null || !code.equals(code_.toString())){
            return JsonResult.paramErrWithMsg("验证码不正确");
        }
        if(EmptyUtils.isEmpty(password)) {
            return JsonResult.paramErrWithMsg("请输入密码");
        }
        if(EmptyUtils.isEmpty(passwords)) {
            return JsonResult.paramErrWithMsg("请输入密码");
        }
        if(!passwords.equals(password)) {
            return JsonResult.paramErrWithMsg("两次密码不一致，请重新输入");
        }
        if(password.length()<8 || password.length()>12){
            return JsonResult.paramErrWithMsg("密码长度必须8到12位");
        }
        sysAdmin.setPassword(PasswordUtil.AESEncrypt(password));
        sysAdmin.setUpdateTime(new Date());
        return JsonResult.success(sysAdminService.updateByPrimaryKeySelective(sysAdmin));
    }

    /**
     * 退出登录
     * @date 2021/5/14 17:15
     * @author caobucao
     * @param request
     * @return com.dzl.util.JsonResult<java.lang.Integer>
     */
    @GetMapping("/logout")
    public JsonResult<Integer> logout(HttpServletRequest request) {
        String token=request.getHeader("token");
        if(EmptyUtils.isEmpty(token)) {
            return JsonResult.fail();
        }
        RedisUtil.delete(token);
        return JsonResult.success();
    }

    /**
     * 获取登录用户详细信息
     * @date 2021/5/17 16:28
     * @author caobucao
     * @return com.dzl.util.JsonResult<com.alibaba.fastjson.JSONObject>
     */
    @GetMapping("queryAdminByToken")
    public JsonResult<LoginSysAdminVo> queryAdminByToken() {
        LoginSysAdminVo loginSysAdminVo = getAdminInfo();
        /*JSONObject obj = new JSONObject();
        SysAdmin sysAdmin = sysAdminService.selectByPrimaryKey(loginSysAdminVo.getId());
        obj.put("phone", loginSysAdminVo.getPhone());
        List<String> permissions= new ArrayList<>();
        List<PermissionVo> permissionList = sysPermissionService.selectPermissionListByRoleId(loginSysAdminVo.getRoleId());
        if(EmptyUtils.isNotEmpty(permissionList)) {
            permissions=permissionList.stream().map(PermissionVo::getCode).collect(Collectors.toList());
        }
        obj.put("userInfo", sysAdmin);
        obj.put("permissions", permissions);*/
        return JsonResult.success(loginSysAdminVo);
    }

    /**
     * 分页查询管理员管理列表数据
     * @date 2021/5/14 9:44
     * @author caobucao
     * @param query 查询条件
     * @return com.dzl.util.JsonResult
     */
    @GetMapping("/querySysAdminListPage")
    public PageUtils<SysAdminVo> querySysAdminListPage(SysAdminQuery query) {
        query.setEnterpriseId(getAdminInfo().getEnterpriseId());
        PageInfo<SysAdminVo> pageInfo = sysAdminService.selectSysAdminListPage(query);
        return new PageUtils<>(pageInfo);
    }

    /**
     * 添加或修改管理员
     * @date 2021/5/13 17:46
     * @author caobucao
     * @param sysAdmin 管理员对象
     * @return com.dzl.util.JsonResult
     */
    @PostMapping("/saveAdmin")
    public JsonResult<Integer> saveAdmin(@RequestBody SysAdmin sysAdmin) {
        if(EmptyUtils.isEmpty(sysAdmin)) {
            return JsonResult.paramErr();
        }
        if(EmptyUtils.isEmpty(sysAdmin.getUserName())) {
            return JsonResult.paramErrWithMsg("请输入管理员姓名");
        }
        if(EmptyUtils.isEmpty(sysAdmin.getRoleId())) {
            return JsonResult.paramErrWithMsg("请选择关联角色");
        }
        /*if(EmptyUtils.isEmpty(""+sysAdmin.getUserStatus())) {
            return JsonResult.paramErrWithMsg("请选择用户状态");
        }*/
        if(EmptyUtils.isEmpty(sysAdmin.getPhone())) {
            return JsonResult.paramErrWithMsg("请输入账号");
        }
        if(EmptyUtils.isEmpty(sysAdmin.getPassword())) {
            return JsonResult.paramErrWithMsg("请输入登录密码");
        }
        Integer loginUserId = getAdminInfo().getId();
        sysAdmin.setUserStatus(1);
        if(EmptyUtils.isEmpty(sysAdmin.getId())) {
            sysAdmin.setUpdater(loginUserId);
            sysAdmin.setCreater(loginUserId);
            sysAdmin.setEnterpriseId(getAdminInfo().getEnterpriseId());
            sysAdmin.setIsAdmin(CommonConstants.NO);
            sysAdmin.setType(CommonConstants.SYS_ADMIN_TYPE.APP);
        } else {
            if(sysAdmin.getId().equals(getAdminInfo().getId())) {
                return JsonResult.paramErrWithMsg("不允许修改本账号信息");
            }
            sysAdmin.setUpdateTime(new Date());
            sysAdmin.setUpdater(loginUserId);
        }
        return JsonResult.success(sysAdminService.saveAdmin(sysAdmin));
    }

    /**
     * 更改用户状态，冻结或解冻
     * @date 2021/5/20 16:25
     * @author caobucao
     * @param query  传入json
     * @return com.dzl.util.JsonResult
     */
    @PostMapping("/updateUserStatus")
    public JsonResult updateUserStatus(@RequestBody JSONObject query) {
        Integer id=query.getInteger("id");
        Integer userStatus=query.getInteger("userStatus");
        SysAdmin sysAdmin = new SysAdmin();
        sysAdmin.setId(id);
        sysAdmin.setUserStatus(userStatus);
        sysAdmin.setUpdater(getAdminInfo().getId());
        sysAdmin.setUpdateTime(new Date());
        return JsonResult.success(sysAdminService.updateByPrimaryKeySelective(sysAdmin));
    }

    /**
     * 删除管理员用户
     * @date 2021/5/13 19:17
     * @author caobucao
     * @param id 用户id
     * @return com.dzl.util.JsonResult
     */
    @DeleteMapping("/deleteSysAdmin")
    public JsonResult deleteSysAdmin(Integer id) {
        SysAdmin sysAdmin = new SysAdmin();
        sysAdmin.setId(id);
        sysAdmin.setStatus(0); //0删除
        sysAdmin.setUpdater(getAdminInfo().getId());
        sysAdmin.setUpdateTime(new Date());
        return JsonResult.success(sysAdminService.updateByPrimaryKeySelective(sysAdmin));
    }



}
